package com.linkage.jz.bankruptcy.push;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.seapeak.activity.message.GoToPageLoadingActivity;

import java.io.Serializable;

/**
 * 如果调用了registerPushIntentService方法注册自定义IntentService，则SDK仅通过IntentService回调推送服务事件；
 * 如果未调用registerPushIntentService方法进行注册，则原有的广播接收器仍然可以继续使用。
 */
public class GTPushIntentService extends GTIntentService {

    public GTPushIntentService() {

    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        // 透传消息的处理，详看SDK demo

        Log.e(TAG, "个推 onReceiveClientMsg-> " + "msg = " + msg.toString());

        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();

        if (payload != null) {
            String content = new String(payload);
            GTCommonMessage message = new Gson().fromJson(content, GTCommonMessage.class);
            Log.e(TAG, "个推 onReceiveClientMsg-> " + "content = " + content);
            addNotification(context, "破晓", message.title, message);
        }
    }

    /**
     * 个推透传创建通知栏
     *
     * @param title
     * @param subtitle
     */
    private void addNotification(Context context, String title, String subtitle, GTCommonMessage message) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //创建通知渠道实例
        //并为它设置属性
        //通知渠道的ID,随便写
        String id = "channel_01";
        int requestCode = (int) System.currentTimeMillis();
        //用户可以看到的通知渠道的名字，R.string.app_name就是strings.xml文件的参数，自定义一个就好了
        CharSequence name = getString(R.string.app_name);
        //用户可看到的通知描述
        String description = getString(R.string.app_name);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //构建NotificationChannel实例
            NotificationChannel notificationChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
            //配置通知渠道的属性
            notificationChannel.setDescription(description);
            //设置通知出现时的闪光灯
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            //设置通知出现时的震动
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 100, 100});
            //在notificationManager中创建通知渠道
            manager.createNotificationChannel(notificationChannel);
        }

        Intent intent = new Intent(context, GoToPageLoadingActivity.class);
        intent.putExtra("id", message.getSysMsgId());
        intent.putExtra("type", 2);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        //蓝色字是个新方法，旧的被api放弃了
        Notification notification = new NotificationCompat.Builder(context, id)
                .setContentIntent(pendingIntent)//设置点击事件 PendingIntent.FLAG_ONE_SHOT: 只有第一次点击有效
                .setContentTitle(title)
                .setContentText(subtitle)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                .setAutoCancel(true)
                .build();
        manager.notify(requestCode, notification);

//        //显示不重复通知
//        int requestCode = (int) System.currentTimeMillis();
//
//        Intent broadcastIntent = new Intent(this, GeTuiNotificationClickReceiver.class);
//        broadcastIntent.putExtra("message", message);
//        PendingIntent pendingIntent = PendingIntent.
//                getBroadcast(this, requestCode, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//
//        Notification.Builder builder = new Notification.Builder(this);
//        builder.setWhen(System.currentTimeMillis())
//                .setContentTitle(title)
//                .setContentText(subtitle)
//                .setDefaults(Notification.DEFAULT_LIGHTS)
//                //.setVibrate(new long[]{0, 300, 300, 300})
//                //设置点击通知跳转页面后，通知消失
//                .setAutoCancel(true)
//                .setContentIntent(pendingIntent);
//        //获取app工程中的图片资源
//        int logoId = getApplicationContext().getResources().getIdentifier(getIconName(getApplicationContext()), "mipmap",
//                getApplicationContext().getPackageName());
//        builder.setSmallIcon(logoId);
//        NotificationManager manager = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
//        manager.notify(requestCode, builder.build());
    }

//    /**
//     * 获取主工程mipmap下的资源文件名
//     */
//    public static String getIconName(Context mContext) {
//        String value = "";
//        try {
//            ApplicationInfo appInfo = mContext.getPackageManager().
//                    getApplicationInfo(mContext.getPackageName(), PackageManager.GET_META_DATA);
//            value = appInfo.metaData.getString("OEM_ICON");
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        return value;
//    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        Log.e(TAG, "个推CID onReceiveClientId -> " + "clientid = " + clientid);
        SPUtils.getInstance(Consts.SPNAME).put("saveCid", clientid);
        String saveCid = SPUtils.getInstance(Consts.SPNAME).getString(GTPushService.CID_TAG, "");
        if (TextUtils.isEmpty(saveCid) || !saveCid.equals(clientid)) {
            GTPushService.saveCid(context, clientid);
        }
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        Log.e(TAG, "个推 onReceiveOnlineState -> " + "online = " + online);
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        Log.e(TAG, "个推 onReceiveCommandResult -> " + "cmdMessage = " + cmdMessage.toString());
    }

    @Override
    public void onNotificationMessageArrived(Context context, GTNotificationMessage msg) {
        Log.e(TAG, "个推 onNotificationMessageArrived -> " + "msg = " + msg.toString());
    }

    @Override
    public void onNotificationMessageClicked(Context context, GTNotificationMessage msg) {
        Log.e(TAG, "个推 onNotificationMessageClicked -> " + "msg = " + msg.toString());
    }


    /**
     * 个推消息
     */
    class GTCommonMessage implements Serializable {


        /**
         * action : 3
         * title : 测试123其他案管理人通知您进行债权申报，请尽快完成债权人操作用户身份验证，进行线上申报。查看详情>
         * params : {"id":"85892d612cb24918bd96ebc8ef04db23","projectId":"33e3ca2732f44e3d86d6be78f00a014d","sendUserId":"0720d92fdaf24411b94a197da3eeb814","fromUserId":"3650a97e25c44e9b8f1c1fb5dcde9d50","sourceUserId":"0720d92fdaf24411b94a197da3eeb814","action":"INVICREDITOR","actionParams":"{\"creditorInfoId\":\"12fc6c1576d94099bc1b3f3f3a1eede7\"}","title":"测试123其他案管理人通知您进行债权申报，请尽快完成债权人操作用户身份验证，进行线上申报。查看详情>","note":"测试123其他案管理人通知您进行债权申报，请尽快完成债权人操作用户身份验证，进行线上申报。查看详情>","msgType":"NOTICE","status":false,"readTime":null,"push":true,"groupNo":null,"invalid":false,"sendUser":null,"fromUser":null,"sourceUser":null,"project":null,"unreadCount":0,"toPage":0,"pageData":null,"href":null,"opBy":"","opAt":1561992553,"delFlag":false}
         * sysMsgId : 85892d612cb24918bd96ebc8ef04db23
         */

        private int action;
        private String title;
        private String params;
        private String sysMsgId;

        public int getAction() {
            return action;
        }

        public void setAction(int action) {
            this.action = action;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getParams() {
            return params;
        }

        public void setParams(String params) {
            this.params = params;
        }

        public String getSysMsgId() {
            return sysMsgId;
        }

        public void setSysMsgId(String sysMsgId) {
            this.sysMsgId = sysMsgId;
        }
    }


}